package com.example.demo.es;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @Create: IntelliJ IDEA.
 * @Author: subtlman_ljx
 * @Date: 2022/08/30/15:51
 * @Description:
 */
@Configuration
@Slf4j
public class RestClientConfig {


    /**
     * es连接
     * @return
     */
    public static RestHighLevelClient restHighLevelClient() {
//        //无用户名密码
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        //有用户名密码
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("elastic",  "Ffcsoss!@#1115"));
        RestHighLevelClient client =
                new RestHighLevelClient(RestClient.builder(
                        new HttpHost("192.168.35.121", 9201, "http"))
                .setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(provider)));
//       //如果是集群
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")
//                        , new HttpHost("127.0.0.1", 9201, "http")
//                        , new HttpHost("127.0.0.1", 9202, "http")));
        return client;
    }

    /**
     * es关闭
     *
     * @param client es客户端
     * @throws IOException io异常
     */
    public static void close(RestHighLevelClient client) {
        try {
            client.close();
        } catch (IOException e) {
        }
    }

    /**
     * 创建索引
     * @param indexNam
     * @return
     */
    public static Boolean createIndex(String indexNam) {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexNam.toLowerCase());
        createIndexRequest.settings(Settings.builder().put("index.number_of_shards", 4)
                .put("index.number_of_replicas", 2));
        try {
            XContentBuilder xContentBuilder= XContentFactory.jsonBuilder();
            xContentBuilder.startObject().startObject("properties")
                    .startObject("type").field("type", "integer").endObject()
                    .startObject("content").field("type", "text").field("analyzer", "ik_max_word").endObject()
                    .endObject().endObject();
            createIndexRequest.mapping(xContentBuilder);
            CreateIndexResponse response = restHighLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
            boolean acknowledged = response.isAcknowledged();
            // 指示是否在超时之前为索引中的每个分片启动了必需的分片副本数
            boolean shardsAcknowledged = response.isShardsAcknowledged();
            if (acknowledged || shardsAcknowledged) {
                log.info("创建索引成功！索引名称为{}", indexNam);
                return Boolean.TRUE;
            }
        } catch (IOException e) {
            log.info("创建索引失败{}",e);
        }
        return Boolean.FALSE;
    }

    /**
     * 是否存在索引
     * @param indexName
     * @return
     */
    public static Boolean isIndexExists(final String indexName) {
        try {
            GetIndexRequest request = new GetIndexRequest(indexName.toLowerCase());
            return restHighLevelClient().indices().exists(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("查看索引是否存在失败{}",e);
            return Boolean.FALSE;
        }
    }

    /**
     * 删除索引
     * @param indexName
     * @return
     */
    public static Boolean removeIndex(String indexName) {
        try {
            DeleteIndexRequest deleteIndexRequest=new DeleteIndexRequest(indexName.toLowerCase());
            AcknowledgedResponse acknowledgedResponse=restHighLevelClient().indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
            if(acknowledgedResponse.isAcknowledged()){
                return Boolean.TRUE;
            }
        } catch (IOException e) {
            log.error("删除索引失败{}",e);
        }
        return Boolean.FALSE;
    }


}
